import Vue from "vue";
import VueRouter from "vue-router";
import Home from "../views/Home.vue";
import store from "@/store";
const originalPush = VueRouter.prototype.push;
//重复点击同一路由地址
VueRouter.prototype.push = function (location) {
  return originalPush.call(this, location).catch((err) => {});
};
Vue.use(VueRouter);

const routes = [
  {
    path: "/",
    redirect: "/home",
  },
  {
    path: "/home",
    name: "home",
    component: Home,
  },
  {
    path: "/goods",
    name: "goods",
    component: () => import("../views/Goods.vue"),
  },
  {
    path: "/user",
    name: "user",
    component: () => import("../views/User.vue"),
    redirect: "/user/cart",
    children: [
      {
        path: "cart",
        component: () => import("../components/user/Cart.vue"),
      },
    ],
    //路由独享守卫，参数和全局守卫一致
    // beforeEnter: (to, from, next) => {
    //   let token = localStorage.getItem["x-auth-token"];
    //   if (token) {
    //     //如果存在正常进入user页面
    //     next();
    //   } else {
    //     //否则提示你还没有登录
    //     // alert("你还没有登录");
    //     store.dispatch("showToast/asyncIsShowToast", {
    //       msg: "你还没有登录",
    //       type: "warning", //提示图标类型
    //     });
    //   }
    //  },
  },
  {
    path: "/order",
    name: "order",
    component: () => import("../views/Order.vue"),
  },
  {
    path: "/free",
    name: "free",
    component: () => import("../views/Free.vue"),
  },
  {
    path: "/details",
    name: "details",
    component: () => import("../views/Details.vue"),
  },
];

const router = new VueRouter({
  mode: "history",
  base: process.env.BASE_URL,
  routes,
});
//导航守卫
// 全局前置守卫
// to: Route: 即将要进入的目标 路由对象
// from: Route: 当前导航正要离开的路由
// next: Function: 一定要调用该方法来 resolve 这个钩子。执行效果依赖 next 方法的调用参数。
/* router.beforeEach((to, from, next) => {
  //如果准备去user页面
  if (to.path == "/user") {
    //则需要获取是否存在token
    let token = localStorage.getItem["x-auth-token"];
    if (token) {
      //如果存在正常进入user页面
      next();
    } else {
      //否则提示你还没有登录
      // alert("你还没有登录");
      store.dispatch("showToast/asyncIsShowToast", {
        msg: "你还没有登录",
        type: "warning", //提示图标类型
      });
    }
    return; //预防代码继续执行下一个next();
  }
  next();
}); */

export default router;
